import {Component, OnInit} from '@angular/core';
import {ProductlistService} from './productlist.service';
import {AliyunOssOutputUrl, appletApiUrl} from '../../../../config/api';
import {Router, ActivatedRoute, ParamMap, NavigationEnd} from '@angular/router';
import 'rxjs/add/operator/switchMap';
import {NzModalService, NzMessageService} from 'ng-zorro-antd';
import {LocalStorageService} from '../../../lib/service/local-storage.service';

@Component({
  selector: 'product-list',
  templateUrl: './productlist.component.html',
  styleUrls: ['./productlist.component.scss'],

})


export class ProductlistComponent implements OnInit {
  groundingVisible = false;//是否上架对话框
  unGroundingVisible = false;//是否下架对话框
  delVisible = false;//是否删除对话框
  _allChecked = false;
  _indeterminate = false;
  order = {
    'created_at': 'desc',
    'price': '',
    'sales_total': ''
  };  // 排序方式
  orderArr = ['created_at'];
  orderJson = {
    price: null,
    sales_total: null
  };
  groupId = 0; // 搜索栏中分组ID
  loading = true;//table 加载状态
  pageSize = 10; //分页条数
  page = 1;//当前页
  total = 0;//总条数
  status = '';  // 当前列表商品的状态
  keyword: string = '';  // 搜索栏中商品名称
  searchValue = '';
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  shopid: any;

  constructor(private ProductlistService: ProductlistService,
              private route: ActivatedRoute,
              private confirmServ: NzModalService,
              private _message: NzMessageService,
              private _router: Router,
              private localStorageService: LocalStorageService,
  ) {
    this._router.events
      .filter((event) => event instanceof NavigationEnd)
      .subscribe((event: NavigationEnd) => {
        if (this.shopid != this.localStorageService.getShop()['id']) {
          this.shopid = this.localStorageService.getShop()['id'];
          this.getGoodsList();
        }

      });
  }

  handleOk1() {

  }

  handleOk(e) {

  }

  sort(type, value) {
    let orderArr = this.orderArr;
    let index = orderArr.indexOf(type);
    if (value) {
      if (index < 0) {
        orderArr.unshift(type);
      }
      this.order[type] = value.substring(0, value.length - 3);
    } else if (this.order[type]) {
      orderArr.splice(index, 1);
      this.order[type] = '';
    }
    this.page = 1;
    this.getGoodsList();
  }

  /*
    *打开上架对话框
    type:上下架类型
    item:当前操作对象 null时 为批量操作
  */
  openGrounding(type = '上架', item = null) {
    let title = '确认要' + type + '此商品？';
    let content = type + '后，此商品会移动至分类' + type + '中';
    let ids = [];

    if (item && item.status != type) { //单个上下架
      ids.push(item.id);
    } else if (!item) { //批量上架
      title = '确认要' + type + '这些商品？';
      content = '上架后，这些商品会移动至分类' + (type == '上架' ? '上架' : '仓库') + '中';
      ids = this.goodsList.filter((item) => {
        return item.checked;
      }).map(item => item.id);
    } else {

      return false;
    }
    this.confirmServ.confirm({
      title,
      // content,
      showConfirmLoading: true,
      onOk: () => {
        return new Promise((resolve) => {
          let _type = 1;
          if (type === '上架') {
            _type = 1;
          } else {
            _type = 0;
          }
          this.changeGoodsStatus(ids, _type, resolve);
        });
      },
      onCancel() {

      }
    });
  }

  productDel(item) {//产品删除
    this.confirmServ.confirm({
      title: '确定要删除该商品？',
      content: '删除后该商品将无法恢复',
      showConfirmLoading: true,
      onOk: () => {
        return new Promise((resolve) => {
          this.ProductlistService.delProduct({shop_id: this.shopid, id: item.id}).subscribe(res => {
            if (res.code === 200) {
              this._message.create('success', '删除成功');
              this.getGoodsList();
              resolve();
            }
          });
        });
      },
      onCancel() {

      }
    });
  }

  ngOnInit() { //初始化
    this.route.params.subscribe((params) => {
      this.shopid = this.localStorageService.getShop()['id'];
      console.log('params-list', params);
      let status = params.type;
      let id = params.classifyId;
      console.log('classifyId', id);
      this.ProductlistService.type1 = status;
      this.ProductlistService.type2 = id;
      this.status = status == 'all' ? '' : status == 'in' ? '上架' : '下架';
      this.groupId = id || 0;
      this.page = 1;
      this.keyword = '';
      this.searchValue = '';
      this.getGoodsList();
    });
  }

  changIndex($event) {
    this.page = $event;
    this.getGoodsList();
  }

  changereset() {//选中状态修改
    this._allChecked = false;
    this._indeterminate = false;
  }

  changeGoodsStatus(ids, status, call = null) {//上下架
    const data = {ids: ids, for_sale: status, shop_id: this.shopid};
    this.ProductlistService.changeGoodsStatus(data).subscribe(res => {
      if (res.code === 200) {
        this.getGoodsList();
      }
      if (typeof call === 'function') {
        this._message.create('success', status + '成功');
        call();
      }
    })
  }

  getGoodsList() {//获取商品列表
    this.loading = true;
    let order = this.order;
    let orderstring = '';
    if (order && (order.price || order.sales_total || order.created_at)) {
      let json = {};
      this.orderArr.forEach(item => {
        json[item] = order[item];
      })
      orderstring = JSON.stringify(json);
    } else {
      orderstring = 'none';
    }
    //this.goodsList=[];
    this.ProductlistService.getGoodsList(this.page, this.pageSize, this.shopid, this.groupId, this.status, orderstring, this.keyword).subscribe(
      res => {
        if (res.code === 200) {
          let goodsList = res.data.data;
          if (goodsList && goodsList.length > 0) {
            this.total = res.data.total;
            this.changereset();
            let goodsid = [];
            goodsList.forEach(item => {
              item.checked = false;
              // if (item.goods_number) {
              //   item.goods_number = item.goods_number.split('|');
              // }
              if (item.pics[0]) {
                item.picture = appletApiUrl + '/common/attachment/view/' + item.pics[0];
              }
              goodsid.push(item.id);
            });
            this.goodsList = goodsList;
            this.loading = false;
            // 请求所属分类
          } else {
            this.goodsList = [];
            this.loading = false;
          }

        }
      });
  }

  keyDown(e) {
    e.code === 'Enter' ? this._submitForm() : '';
  }

  goodsList = [];  // 商品列表
  _submitForm() {//搜索
    this.keyword = this.searchValue;//搜索
    console.log('keyword', this.keyword);
    this.page = 1;
    this.getGoodsList();
  }

  resetForm(e) {
    e.preventDefault();
    this.keyword = this.searchValue = '';
    this.page = 1;
    this.getGoodsList();
  }

  _checkAll(value) {
    if (value) {
      this.goodsList.forEach(item => {
        item.checked = true;
      });
    } else {
      this.goodsList.forEach(item => {
        item.checked = false;
      });
    }
    this._refreshStatus();
  };

  _refreshStatus() {
    const allChecked = this.goodsList.every(value => value.checked === true);
    const allUnChecked = this.goodsList.every(value => !value.checked);
    this._allChecked = allChecked;

    this._indeterminate = (!allChecked) && (!allUnChecked);
  };
}
